package com.hd.determine.core.task;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.hd.common.constant.BizConstant;
import com.hd.common.utils.CollectionUtils;
import com.hd.common.utils.ValueUtils;
import com.hd.determine.config.rabbitmq.producer.RabbitProducer;
import com.hd.determine.config.redis.prefix.CacheKey;
import com.hd.determine.config.redis.utils.JedisUtil;
import com.hd.determine.modules.vehicle.model.VehicleEndPos;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;


/**
 * @author chentl
 * @version V1.0
 * @Project 交通运输第三方监测平台
 * @Title ScheduledTasks.java
 * @Description SpringBoot定时任务工具类
 * 各定时任务执行频率:
 * 主动报警研判 50min
 * 末次位置信息更新 15min
 * 静态车辆数据同步 20min
 * 自动统计 sp_alarm_daily_statis              3min
 * 自动统计 sp_vehicle_alarm_daily_statis      4min
 * 自动统计 sp_vehicle_daily_statis            5min
 * @Package com.hd.sup.core.task
 * @date 2021/1/14 1:54 下午
 * @Copyright: 深圳市宏电技术股份有限公司 All rights reserved.
 */
@Slf4j
@Component
public class ScheduledTasks {

    @Resource
    private RabbitProducer rabbitProducer;

    @Resource
    private JedisUtil jedisUtil;

    /**
     * @return void
     * @author chentl
     * @description 10min 执行一次
     * @date 2021/1/7 4:27 下午
     * @params []
     */
//    @Scheduled(cron = "0 0 0/2 * * ?")
    public void alarmDetermine() {
        log.info("[schedule] 【报警研判】定时任务执行");
        //查询所有末次信息
        Set<String> keyList = (Set<String>) jedisUtil.getKeys(CacheKey.END_POSITION_KEY);
        if (CollectionUtils.isEmpty(keyList)) return;

        List<String> resultList = jedisUtil.mget(keyList.toArray(new String[]{}));
        if (CollectionUtils.isEmpty(resultList)) return;

        //定时任务产生的主动研判标识
        List<String> newResultList = Lists.newArrayList();
        for (String s : resultList) {
            VehicleEndPos obj = JSON.parseObject(s, VehicleEndPos.class);
            String alarm_type = ValueUtils.parseString(obj.getAlarmType());

            if (alarm_type.equals(BizConstant.AlarmType.OVER_SPEED.key())
                    || alarm_type.equals(BizConstant.AlarmType.OFF_GPS.key())
                    || alarm_type.equals(BizConstant.AlarmType.OFF_LINE.key()))
                continue;

            obj.setScheduled(true);
            newResultList.add(JSON.toJSONString(obj));
        }


        //遍历末次信息Set 同时拼接sql
        newResultList.forEach(one -> rabbitProducer.sendToAlarmDetailQueue(ValueUtils.parseString(one)));

        log.info("[schedule] 【报警研判】定时任务结束");
    }


}
